﻿//--------------------------------------------------------------------
// All Rights Reserved , Copyright (C) 2011 , Hairihan TECH, Ltd. 
//--------------------------------------------------------------------

using System;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace DotNet.WinForm.Utilities
{
    using DotNet.Model;
    using DotNet.Service;
    using DotNet.Utilities;

    /// <summary>
    /// BaseForm
    /// 
    /// 修改纪录
    ///
    ///		2008.04.21 版本：1.1 JiRiGaLa 用户重新登录，扮演时的错误进行修正。
    ///		2008.01.11 版本：1.0 JiRiGaLa 创建。
    ///		
    /// 版本：1.1
    ///
    /// <author>
    ///		<name>JiRiGaLa</name>
    ///		<date>2008.04.21</date>
    /// </author> 
    /// </summary>
    public class BaseForm : Form
    {
        public BaseForm()
        {
            if (!this.DesignMode)
            {
                this.GetIcon(); // 必须放在初始化组件之前
            }
            InitializeComponent();
        }

        public virtual void GetIcon()
        {
            if (System.IO.File.Exists(BaseSystemInfo.FormIco))
            {
                this.Icon = new Icon(BaseSystemInfo.FormIco);
            }
        }

        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(BaseForm));
            this.SuspendLayout();
            // 
            // BaseForm
            // 
            this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage")));
            this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
            this.ClientSize = new System.Drawing.Size(642, 365);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.KeyPreview = true;
            this.Name = "BaseForm";
            this.ShowInTaskbar = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Load += new System.EventHandler(this.Form_Load);
            this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form_FormClosed);
            this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form_KeyDown);
            this.ResumeLayout(false);

        }

        #region public virtual void GetPermission() 获得页面的权限
        /// <summary>
        /// 获得页面的权限
        /// </summary>
        public virtual void GetPermission()
        {
        }
        #endregion

        #region public virtual void SetControlState() 设置按钮状态
        /// <summary>
        /// 设置按钮状态
        /// </summary>
        public virtual void SetControlState()
        {
        }
        #endregion

        #region public virtual void SetControlState(bool enabled) 设置按钮状态
        /// <summary>
        /// 设置按钮状态
        /// </summary>
        /// <param name="enabled">有效</param>
        public virtual void SetControlState(bool enabled)
        {
        }
        #endregion

        #region public virtual void SetHelp() 设置帮助
        /// <summary>
        /// 设置帮助
        /// </summary>
        public virtual void SetHelp()
        {
        }
        #endregion

        #region public virtual void ShowEntity() 显示内容
        /// <summary>
        /// 显示内容
        /// </summary>
        public virtual void ShowEntity()
        {
        }
        #endregion

        #region public virtual void GetList() 获得列表数据
        /// <summary>
        /// 获得列表数据
        /// </summary>
        public virtual void GetList()
        {
        }
        #endregion

        #region public virtual bool CheckInput() 检查输入的有效性
        /// <summary>
        /// 检查输入的有效性
        /// </summary>
        /// <returns>有效</returns>
        public virtual bool CheckInput()
        {
            return true;
        }
        #endregion

        #region public virtual bool SaveEntity() 保存
        /// <summary>
        /// 保存
        /// </summary>
        /// <returns>保存成功</returns>
        public virtual bool SaveEntity()
        {
            return true;
        }
        #endregion

        #region public virtual int BatchDelete() 批量删除
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <returns>影响行数</returns>
        public virtual int BatchDelete()
        {
            return 0;
        }
        #endregion

        #region public virtual bool CheckInputDelete() 检查批量删除
        /// <summary>
        /// 检查批量删除
        /// </summary>
        /// <returns>允许删除</returns>
        public virtual bool CheckInputDelete()
        {
            return true;
        }
        #endregion

        #region public bool IsAuthorized(string permissionItemCode) 是否有相应的权限
        /// <summary>
        /// 是否有相应的权限
        /// </summary>
        /// <param name="permissionItemCode">权限编号</param>
        /// <returns>有权限</returns>
        public bool IsAuthorized(string permissionItemCode)
        {
            // 默认为了安全起见、设置为无权限比较好
            bool returnValue = false;
            // 先判断用户是否超级管理员，若是超级管理员，就不用判断操作权限了（这个是有点儿C/S的特色）
            if (UserInfo.IsAdministrator)
            {
                return true;
            }

            /*            
            // 这里是判断本地缓存里，操作权限是否为空？
            if (ClientCache.Instance.DTPermission == null)
            {
                // return false;
                // 重新读取本地缓存里的操作权限
                ClientCache.Instance.GetPermission(this.UserInfo);
            }            
            // 直接判断是否有相应的操作权限
            returnValue = BaseBusinessLogic.IsAuthorized(ClientCache.Instance.DTPermission, permissionItemCode);
            if (returnValue))
            {
                return true;
            }            
            returnValue = BaseBusinessLogic.IsAuthorized(ClientCache.Instance.DTPermission, permissionItemCode);

            // 查看看是否设置了操作权限映射关系表
            string fileName = Application.StartupPath + "\\" + "PermissionMapping.xml";
            if (System.IO.File.Exists(fileName))
            {
                // 获得映射的操作权限编号
                string code = ConfigHelper.GetValue(fileName, permissionItemCode);
                if (!String.IsNullOrEmpty(code))
                {
                    permissionItemCode = code;
                }
            }
            */

            // 虽然这样读取权限效率低一些，但是会及时性高一些，例如这个时候正好权限被调整了
            // 这里是在服务器上进行权限判断，远程进行权限判断（B/S的都用这个方法直接判断权限）
            if (!returnValue)
            {
                returnValue = ServiceManager.Instance.PermissionService.IsAuthorizedByUser(this.UserInfo, this.UserInfo.Id, permissionItemCode);
            }
            return returnValue;
        }
        #endregion

        public void WriteException(Exception ex)
        {
            // 在本地记录异常
            FileUtil.WriteException(UserInfo, ex);
        }

        /// <summary>
        /// 处理异常信息
        /// </summary>
        /// <param name="exception">异常</param>
        public void ProcessException(Exception ex)
        {
            this.WriteException(ex);
            // 显示异常页面
            FrmException frmException = new FrmException(ex);
            frmException.ShowDialog();
        }

        private string entityId = string.Empty;
        /// <summary>
        /// 实体主键
        /// </summary>
        public virtual string EntityId
        {
            get
            {
                return this.entityId;
            }
            set
            {
                this.entityId = value;
            }
        }        

        /// <summary>
        /// 是否退出应用程序
        /// </summary>
        public bool ExitApplication = false;

        /// <summary>
        /// 窗体已经加载完毕
        /// </summary>
        public bool FormLoaded      = false;

        /// <summary>
        /// 是否忙碌状态
        /// </summary>
        public bool Busyness        = false;
        
        /// <summary>
        /// 数据发生过变化
        /// </summary>
        public bool Changed         = false;

        /// <summary>
        /// 设置按钮的可用状态
        /// </summary>
        /// <param name="setTop">置顶</param>
        /// <param name="setUp">上移</param>
        /// <param name="setDown">下移</param>
        /// <param name="setBottom">置底</param>
        /// <param name="add">添加</param>
        /// <param name="edit">编辑</param>
        /// <param name="batchDelete">批量删除</param>
        /// <param name="batchSave">批量保存</param>
        public delegate void SetControlStateEventHandler(bool setTop, bool setUp, bool setDown, bool setBottom, bool add, bool edit, bool batchDelete, bool batchSave);

        /// <summary>
        /// 当前操作员信息
        /// 这里表示是只读的
        /// </summary>
        public BaseUserInfo UserInfo
        {
            get
            {
                return BaseSystemInfo.UserInfo;
            }
        }

        #region public void Localization(Form form) 多语言国际化加载
        /// <summary>
        /// 多语言国际化加载
        /// </summary>
        public void Localization(Form form)
        {
            BaseInterfaceLogic.SetLanguageResource(form);
        }
        #endregion

        public virtual void Form_KeyDown(object sender, KeyEventArgs e)
        {
            // 按键事件
            if (e.KeyCode == Keys.F5)
            {
                // F5刷新，重新加载窗体
                this.FormOnLoad();
            }
            else
            {
                // 按了回车按钮处理光标焦点
                if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
                {
                    if ((this.ActiveControl is TextBox) || (this.ActiveControl is ComboBox))
                    {
                        if ((this.ActiveControl is TextBox) && ((TextBox)this.ActiveControl).Multiline)
                        {
                            return;
                        }
                        SendKeys.Send("{TAB}");
                    }
                }
            }
        }
        
        #region public virtual void FormOnLoad() 加载窗体
        /// <summary>
        /// 加载窗体
        /// </summary>
        public virtual void FormOnLoad()
        {
            if (!this.DesignMode)
            {
                // 是否记录访问日志
                if (BaseSystemInfo.RecordLog)
                {
                    // 已经登录了系统了，才记录日志
                    if (BaseSystemInfo.LogOned)
                    {
                        // 调用服务事件
                        ServiceManager.Instance.LogService.WriteLog(UserInfo, this.Name, this.Text, "FormLoad");
                    }
                }
                // 多语言国际化加载
                this.Localization(this);
            }
        }
        #endregion

        public virtual void Form_Load(object sender, EventArgs e)
        {
            if (!this.DesignMode)
            {
                // 设置鼠标繁忙状态
                this.Cursor = Cursors.WaitCursor;
                this.FormLoaded = false;
                try
                {
                    // 必须放在初始化组件之前
                    this.GetIcon();
                    // 获得页面的权限
                    this.GetPermission();
                    // 加载窗体
                    this.FormOnLoad();
                    // 设置按钮状态
                    this.SetControlState();
                    // 设置帮助
                    this.SetHelp();
                    // 多语言国际化加载
                    this.Localization(this);
                }
                catch (Exception ex)
                {
                    this.ProcessException(ex);
                }
                finally
                {
                    this.FormLoaded = true;
                    // 设置鼠标默认状态
                    this.Cursor = Cursors.Default;
                }
            }
        }

        /// <summary>
        /// 获取组织机构权限域数据
        /// </summary>
        public DataTable GetOrganizeScope(string permissionItemCode)
        {
            // 获取部门数据，不启用权限域
            if ((UserInfo.IsAdministrator) || (String.IsNullOrEmpty(permissionItemCode) || (!BaseSystemInfo.UsePermissionScope)))
            {
                DataTable dataTable = ClientCache.Instance.GetOrganizeDT(UserInfo).Copy();
                dataTable.DefaultView.Sort = BaseOrganizeTable.FieldSortCode;
                return dataTable;
            }
            else
            {
                return ServiceManager.Instance.PermissionService.GetOrganizeDTByPermission(UserInfo, UserInfo.Id, permissionItemCode);
            }
        }

        /// <summary>
        /// 获取职员权限域数据
        /// </summary>
        public DataTable GetUserScope(string permissionItemCode)
        {
            // 获取部门数据
            if ((UserInfo.IsAdministrator) || (String.IsNullOrEmpty(permissionItemCode)))
            {
                return ServiceManager.Instance.UserService.GetDT(UserInfo);
            }
            else
            {
                return ServiceManager.Instance.PermissionService.GetUserDTByPermission(UserInfo, UserInfo.Id, permissionItemCode);
            }
        }

        /// <summary>
        /// 获取授权范围数据 （按道理，应该是在某个数据区域上起作用）
        /// </summary>
        public DataTable GetPermissionLicensed()
        {
            // 获取部门数据
            if (UserInfo.IsAdministrator)
            {
                return ServiceManager.Instance.PermissionItemService.GetDT(UserInfo);
            }
            else
            {
                return ServiceManager.Instance.PermissionService.GetLicensePermissionByUser(UserInfo, UserInfo.Id);
            }
        }

        #region public bool ModuleIsVisible(string moduleCode) 模块是否可见
        /// <summary>
        /// 模块是否可见
        /// </summary>
        /// <param name="moduleCode">模块编号</param>
        /// <returns>有权限</returns>
        public bool ModuleIsVisible(string moduleCode)
        {
            bool returnValue = false;
            foreach (DataRow dataRow in ClientCache.Instance.DTMoule.Rows)
            {
                if (dataRow[BaseModuleTable.FieldCode].ToString().Equals(moduleCode))
                {
                    returnValue = dataRow[BaseModuleTable.FieldEnabled].ToString().Equals("1");
                    break;
                }
            }
            // 模块是否可见;
            return returnValue;
        }
        #endregion

        #region public bool ModuleIsAuthorized(string moduleCode) 模块是否有权限访问
        /// <summary>
        /// 模块是否有权限访问
        /// </summary>
        /// <param name="moduleCode">模块编号</param>
        /// <returns>有权限</returns>
        public bool ModuleIsAuthorized(string moduleCode)
        {
            bool returnValue = false;
            // 1：是否超级管理员？若是超级管理员，什么模块都是能访问的，这是为了提高判断程序的执行效率
            if (this.UserInfo.IsAdministrator)
            {
                returnValue = true;
                return returnValue;
            }
            // 2：是否已经设置为公开？公开的模块谁都可以访问的
            foreach (DataRow dataRow in ClientCache.Instance.DTMoule.Rows)
            {
                if (dataRow[BaseModuleTable.FieldCode].ToString().Equals(moduleCode))
                {
                    returnValue = dataRow[BaseModuleTable.FieldIsPublic].ToString().Equals("1");
                    break;
                }
            }
            // 3：当前用户是否有模块访问权限？（已包含用户的、角色的模块访问权限）
            if (!returnValue)
            {
                foreach (DataRow dataRow in ClientCache.Instance.DTUserMoule.Rows)
                {
                    if (dataRow[BaseModuleTable.FieldCode].ToString().Equals(moduleCode))
                    {
                        returnValue = true;
                        break;
                    }
                }
            }
            return returnValue;
        }
        #endregion

        #region private bool FileExist(string fileName) 检查文件是否存在
        /// <summary>
        /// 检查文件是否存在
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns>是否存在</returns>
        private bool FileExist(string fileName)
        {
            if (System.IO.File.Exists(fileName))
            {
                string targetFileName = System.IO.Path.GetFileName(fileName);
                if (MessageBox.Show(AppMessage.Format(AppMessage.MSG0236, targetFileName), AppMessage.MSG0000, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    System.IO.File.Delete(fileName);
                }
                else
                {
                    return true;
                }
            }
            return false;
        }
        #endregion

        #region private void ExportExcel(DataGridView dataGridView, string directory, string fileName) 导出Excel
        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="DataGridView">数据表格</param>
        /// <param name="directory">目录</param>
        /// <param name="fileName">文件名</param>
        public void ExportExcel(DataGridView dataGridView, string directory, string fileName)
        {
            // 开始忙了
            this.Cursor = Cursors.WaitCursor;
            string directoryName = BaseSystemInfo.StartupPath + directory;
            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
            string file = BaseSystemInfo.StartupPath + directory + fileName;
            if (!this.FileExist(file))
            {
                BaseExportCSV.ExportCSV(dataGridView, file);
                Process.Start(file);
            }
            // 已经忙完了
            this.Cursor = Cursors.Default;
        }
        #endregion

        #region private void FormOnClosed() 关闭窗体
        /// <summary>
        /// 关闭窗体
        /// </summary>
        private void FormOnClosed()
        {
            if (!this.DesignMode)
            {
                // 是否记录访问日志，已经登录了系统了，才记录日志
                if (BaseSystemInfo.LogOned && BaseSystemInfo.RecordLog)
                {
                    if (BaseSystemInfo.LogOned)
                    {
                        // 调用服务事件
                        ServiceManager.Instance.LogService.WriteLog(UserInfo, this.Name, this.Text, "FormClosed");
                    }
                }
            }
        }
        #endregion

        private void Form_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (!this.DesignMode)
            {
                // 设置鼠标繁忙状态
                this.Cursor = Cursors.WaitCursor;
                try
                {
                    this.FormOnClosed();
                }
                catch (Exception ex)
                {
                    this.ProcessException(ex);
                }
                finally
                {
                    // 设置鼠标默认状态
                    this.Cursor = Cursors.Default;
                }
            }
        }
    }
}